//
//  HLSquareView.m
//  YueYue
//
//  Created by hulu001 on 2023/5/31.
//

#import "HLSquareView.h"
#import "HLSquareUserCell.h"
#import "HLUserDetailViewController.h"
#import "HLSquareUserModel.h"
#import "HLSquareListRequest.h"
#import "UIScrollView+ScrollAnimation.h"

@interface HLSquareView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) HLSquareListRequest *request;
@property (nonatomic, strong) NSArray <HLSquareUserModel*>*users;
@property (nonatomic, strong) NSString *timeSquareKey;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, assign) NSInteger totalItemCount;
@property (nonatomic, assign) BOOL isLeft;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) BOOL isRequesting;

@end

@implementation HLSquareView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
    }
    return self;
}

- (void)setupView {
    
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 4;
    _flowLayout.minimumInteritemSpacing = 4;
    
    CGFloat itemW = SCREEN_WIDTH / 2.2;
    
    _flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _flowLayout.itemSize = CGSizeMake(itemW, itemW * 1.2);
        //设置代理，实现代理方法
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    _collectionView.pagingEnabled = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = UIColorClear;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[HLSquareUserCell class] forCellWithReuseIdentifier:[HLSquareUserCell identifyCell]];
    [self addSubview:_collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(4);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(itemW * 1.2);
        make.bottom.mas_equalTo(-4);
    }];
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.totalItemCount;
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HLSquareUserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[HLSquareUserCell identifyCell] forIndexPath:indexPath];
    long itemIndex = indexPath.item % _users.count;
    cell.model = self.users[itemIndex];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    long itemIndex = indexPath.item % _users.count;
    HLSquareUserModel *model = self.users[itemIndex];
    HLUserInfoModel *user = [[HLUserInfoModel alloc] init];
    user.userId = model.customerId;
    user.videoType = [model videoType];
    [HLUIHelper callWithUser:user];
}

- (void)setModel:(HLSquareModel *)model
{
    _model = model;
    self.request = [[HLSquareListRequest alloc] initWithCode:model.tag.tagCode];
    [self requestSquare];
}

- (void)requestSquare
{
    if (self.isRequesting || (HLRunTime.shareInstance.mine == nil)){
        return;
    }
    
    self.isRequesting = YES;
    [self.request startWithCompletionBlockWithSuccess:^(__kindof HLSquareListRequest * _Nonnull request) {
        if (request.isSuccess){
            NSArray *users = [request squareList];
            if (users.count > 0){
                self.users = users;
                self.isLeft = self.model.index % 2;
                self.totalItemCount = users.count * 10;
                [self.collectionView reloadData];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self animateWithCollection];
                });

            } else {
                if (self.users > 0){
                    [self animateWithCollection];
                }
            }
        }
    } failure:nil];
}


- (void)animateWithCollection
{
    self.isRequesting = NO;
    CGFloat itemW = SCREEN_WIDTH / 2.2 + 4;
    NSInteger animateCount = (self.totalItemCount - 3);
    CAMediaTimingFunction *timing = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    CGFloat animateTo = animateCount * itemW;
    if (self.isLeft){
        [self.collectionView setContentOffset:CGPointZero];
        [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x + animateTo, self.collectionView.contentOffset.y) withTimingFunction:timing duration:(animateCount * 2.2)];
    } else {
        [self.collectionView setContentOffset:CGPointMake(animateTo - (arc4random_uniform(4) * itemW), 0)];
        [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x - animateTo + itemW * 3, self.collectionView.contentOffset.y) withTimingFunction:timing duration:(animateCount * 2.2)];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self requestSquare];
}

@end
